import express from 'express';
import session from 'express-session';
import datasource from './framework/datasource';
import urls from './urls';

// 注册dao
import './word/dao/WorkDao';
import './word/dao/WarningDao'
import './system/dao/UserDao';
import { Result } from 'spen-common/src/Result';
datasource.sync();

function main(){
    const app: express.Application = express();
    app.use(express.json())
    app.use(session({
        secret: 'your_secret_key',
        resave: false,
        saveUninitialized: true,
        cookie: {
            secure: false
        }
    }));
    for (let i in urls) {
        if(urls[i].type == 'router'){
            app.use(i, urls[i].application )
        }
        if(urls[i].type == 'filter'){
            app.use(urls[i].application)
        } 
    }

    app.use((err: any, req: any, res: any, next: any) => {
        console.error(err.stack); 
        res.status(500).send(<Result>{
            code: 'error',
            msg: '内部异常'
        }); 
    });

    app.listen(3000, async() => {
        console.log(`\n\n  \x1b[32m服务已经启动 \n\n  \x1b[32m➜  \x1b[0mLocal:\t\x1b[36mhttp://localhost:${3000}\x1b[0m \n`);
        try {
            await datasource.authenticate();
            console.log('  \x1b[32mConnection has been established successfully.\x1b[0m\n\n');
        } catch (error) {
            console.error('\x1b[31mUnable to connect to the database:\x1b[0m', error);
        }
    });
}

process.on("exit", ()=>{
    datasource.close();
})
process.on('SIGTERM', ()=>{
    console.log("SIGTERM");
    datasource.close();
})
process.on('SIGINT', ()=>{
    console.log("SIGINT");
    datasource.close();
})
main()